<template>
  <div>
    <el-upload v-model:file-list="fileList" action="/system/system/v2/file/upload" :accept="accept"
      list-type="picture-card" :headers="{
        Authorization: formatToken(getToken()?.accessToken)
      }" :multiple="limit > 1" v-bind="$attrs" :limit="limit" :class="{
        'upload-is-view': (limit === 1 && fileList.length > 0) || isView
      }" :before-upload="beforeupload" :on-success="handlerSuccess" :on-exceed="handlerExceed" :on-error="onError" :on-change="onchange">
      <div class="flex flex-col justify-center items-center">
        <el-icon>
          <Plus />
        </el-icon>

        <small class="text-gray-400">{{ tips }}</small>

      </div>
      <template #file="scope">
        <div class="file-image ">

          <el-image v-if="scope.file.status != 'uploading'" :key="scope.file.url" :src="scope.file.url" :zoom-rate="1.2"
            @click="previewHandler(scope.file)" preview-teleported :preview-src-list="srcList"
            :initial-index="initIndex" fit="cover">
            <template #error>
              <img src="@/assets/screenimg/null.png" />
            </template>
          </el-image>
          <div class="progress" v-if="scope.file.status === 'uploading'">
            <el-progress type="circle" :percentage="Number(
              scope.file.percentage === 100 ? 99 : scope.file.percentage
            )
              " />
          </div>

          <div class="file-image-action transition hover:!bg-[#00000049]"
            v-if="!isView && scope.file.status === 'success'">
            <el-icon @click="removeHandler(scope.file, scope)">
              <Delete />
            </el-icon>
          </div>
        </div>

      </template>

    </el-upload>
    <div class="!mt-[0px]" v-if="isText">
      <el-text class="!text-[red] ">
        注: 图片尺寸为 586*42px
      </el-text>
    </div>


  </div>
</template>

<script setup lang="ts">
import { ref, watch, watchEffect } from "vue";
import { Delete, Plus } from "@element-plus/icons-vue";

import { ElMessage, type UploadProps, type UploadUserFile } from "element-plus";
import { formatToken, getToken } from "@/utils/auth";
import { removeFileApi } from "@/api/user";
import { message, useMessage } from "@/utils/message";
import { getImageInfo } from "@/utils/functions";
// import { thumbImg } from "@/utils/functions";

interface Props {
  files?: UploadUserFile[] | string;
  fileList?: UploadUserFile[];
  limit?: number;
  isView?: boolean;
  fileSize?: number;
  tips?: string;
  osType?: string;
  isText?: boolean;
  accept?: string;
}

const emits = defineEmits(["update:files", "update:fileList"]);
const props = withDefaults(defineProps<Props>(), {
  files: () => [],
  isView: false,
  limit: 6,
  fileSize: 0,
  tips: "",
  isText: false,
  osType: "qiniu",
  accept: '.jpg,.jpeg,.png,.gif,.webp,.svg'
});
const srcList = ref([]);
/**
 * @description:  接收和上传的数据类型共有三种, 1: 字符串, 2: 字符串数组, 3: 空字符串
 * @description:  显示的数据类型: [{url: 'http://xxx.com/xxx.jpg'}]
 */
const fileReset = (files: any) => {
  // console.log("fileReset", files);
  // 无数据验证: 是空的类型
  if (files === "" || !files) return [];
  // 无数据验证: 是[]
  if (Array.isArray(files) && files.length === 0) return [];

  // 有数据验证: 是字符串类型 http://xxx.com/xxx.jpg
  if (typeof files === "string") {
    return [{ url: files, success: "success" }];
  }
  //  有数据验证: 是数组类型
  // [http://xxx.com/xxx.jpg, http://xxx.com/xxx.jpg]
  // [{name: 'xxx', response: {res: 'http://xxx.com/xxx.jpg'}}]
  if (Array.isArray(files) && files.length !== 0) {
    return files.map(file => {
      if (typeof file === "string") {
        return { url: file, success: "success" };
      }
      if (typeof file === "object") {
        // console.log("file", file);
        const response = file.response;
        // console.log("response", response);
        if (!response) {
        } else {
          file.url = response.result;
        }
        return response
          ? { url: response.result, uid: file.uid, success: "success" }
          : { url: file.url, uid: file.uid, success: "success" };
      }
    });
  }
  return [];
};
const fileList = ref(fileReset(props.files));

watchEffect(
  () => {
    srcList.value = fileList.value.map(item => item.url) || [];
  },
  { flush: "post" }
);

watch(
  () => props.files,
  file => {
    if (!file || file.length === 0) {
      fileList.value = [];
    } else {
      srcList.value = fileList.value.map(item => item.url) || [];
      fileList.value = fileReset(file);
    }
  }
);
const initIndex = ref(0);

/**
 * @description: 查看图片
 */
const previewHandler: UploadProps["onPreview"] = file => {
  initIndex.value = srcList.value.indexOf(file.url);
};
/**
 * @description: 删除图片
 */
const removeHandler: UploadProps["onRemove"] = file => {
  const index = fileList.value.findIndex(item => item.url === file.url);
  fileList.value.splice(index, 1);
  srcList.value.splice(index, 1);
  emitFileHandler();

  removeFileApi(
    {
      fileUrl: file.url
    }
    // repson ? {fileUrl: repson.result.fileUrl} : {fileUrl: file.url}
  );
};

const handlerExceed: UploadProps["onExceed"] = () => {
  message("已超过最大上传限制数", {
    type: "warning"
  });
};
const beforeupload = (file) => {
  if (props.accept == '.') {
    return true;
  }
  let names = file.name.split(".")
  let extension = `.${names[names.length - 1]}`;
  let extensionList = props.accept.split(",");
  if (extensionList.indexOf(extension) < 0) {
    ElMessage({
      type: 'error',
      message: '文件格式错误',
    })
    return false;
  }
}
const onError: UploadProps["onError"] = () => {
  message("上传失败", {
    type: "error"
  });
};

// async
const onchange = (file, fileList) => {
  // 1、判断文件大小是否合法，文件限制不能大于10M
  const size = file.size / 1024 / 1024;
  if (props.fileSize > 0) {
    if (size > props.fileSize) {
      let msgSize = `${props.fileSize}M`;
      if (props.fileSize < 1) {
        msgSize = `${props.fileSize * 1024}KB`;
      }
      useMessage().error(`上传文件大小不能超过 ${msgSize}!`);
      fileList.value.splice(-1, 1); //移除当前超出大小的文件
      return false;
    }
  }
  console.log("props.isText", props.isText);

  // if(props.isText == true){
  //   console.log(await imgSize(file.url));
  // }

};

const imgSize = (img) => {
  let width = 470
  let height = 42
  return new Promise((resolve, reject) => {
    getImageInfo(img).then(res => {
      if (res.width > width || res.height > height) {
        resolve(false)
        useMessage().error(`上传图片尺寸错误`);
        fileList.value.splice(-1, 1);
        return false;
      }
      resolve(true)
    })
  });
}


/**
 * @description: 发送数据
 */
const emitFileHandler = () => {


  const files = fileReset(fileList.value).map(item => item.url);
  if (props.limit === 1) {
    emits("update:files", files.at(0));
    console.log('文件上传成功了');
  } else {
    emits("update:files", files);
  }
};

const handlerSuccess = e => {
  // fileList.value.push({
  //   success: 'success',
  //   url: e.result
  // })
  emitFileHandler();
};
</script>

<style scoped lang="scss">
.file-image {
  position: relative;
  flex: 1;

  .el-image {
    height: 100%;
    width: 100%;
  }

  .file-image-action {
    width: 100%;
    height: 20px;
    background: rgba(0, 0, 0, 0.5);
    color: #fff;
    position: absolute;
    bottom: 0;
    left: 0;
    z-index: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    border-top-left-radius: 2px;
    border-top-right-radius: 2px;
  }

  .el-icon {
    z-index: 2;
    cursor: pointer;
  }
}

.upload-is-view {
  ::v-deep .el-upload--picture-card {
    display: none;
  }
}

// ::v-deep.el-upload--picture-card {
// width: 470px !important;
// height: 42px !important;
// }</style>
